package com.irdstudio.efp.esb.service.impl.zx;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.irdstudio.basic.framework.core.constant.CertTypeConstant;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.core.util.Try;
import com.irdstudio.cdp.pboc.service.facade.*;
import com.irdstudio.cdp.pboc.service.vo.*;
import com.irdstudio.efp.esb.common.constant.ESBTradeNoConstance;
import com.irdstudio.efp.esb.common.constant.ZXReturnType;
import com.irdstudio.efp.esb.service.bo.req.BaseNewZXReqBean;
import com.irdstudio.efp.esb.service.bo.req.BaseZXReqBean;
import com.irdstudio.efp.esb.service.bo.req.ZX10001QueryReports;
import com.irdstudio.efp.esb.service.bo.req.ZXCXA01QueryReports;
import com.irdstudio.efp.esb.service.bo.req.ZXCXA01QueryReports.Builder;
import com.irdstudio.efp.esb.service.bo.resp.zx.BaseNewZXResBean;
import com.irdstudio.efp.esb.service.bo.resp.zx.ZXCXA01ResponseReport;
import com.irdstudio.efp.esb.service.vo.zx.ZXVO;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

/**
 * @description:二代征信单笔查询接口 html,xml,json
 * @date:2020年01月22日
 * @author:dengqiwen
 */
@Service("zxCXA01Service")
public class ZXCXA01ServiceImpl extends BaseNewZXService<ZXCXA01QueryReports, ZXCXA01ResponseReport> {

	private static Logger log = LoggerFactory.getLogger(ZXCXA01ServiceImpl.class);
	public static final String INTERFACE_ID = "10001";
	private final String vertType = "30";

	@Override
	protected void preProcess(BaseNewZXReqBean<ZXCXA01QueryReports> reqBean) {
		/*ZXCXA01QueryReports queryReports = reqBean.getQryRptsInfArry().get(0);
		queryReports = new Builder()
				.buildWithExists(queryReports)
				.withIntfInd(INTERFACE_ID)
				.withRptFmt(vertType)
				.withRptAgng(config.getValidDay())
				.withRtnType(ZXReturnType.JSON.VALUE)
				.withCertTp(CertTypeConstant.CODE_10100)
				.build();
		queryReports = new Builder().buildWithExists(queryReports).build();
		log.debug("进入征信单笔查询接口，参数：" + Objects.toString(queryReports));*/
	}

	@Override
	protected String tradeNo() {
		return ESBTradeNoConstance.ZXCXA01;
	}

	@Override
	protected String scene() {
		return "01";
	}

	@Override
	protected Function<String, BaseNewZXResBean<ZXCXA01ResponseReport>> converter() {
		return i -> JSONObject.parseObject(i, new TypeReference<BaseNewZXResBean<ZXCXA01ResponseReport>>() {});
	}

	@Autowired
	@Qualifier("zxJsonInfoService")
	private ZXJsonInfoService zxJsonInfoService;
	@Autowired
	@Qualifier("zxHtmlInfoService")
	private ZXHtmlInfoService zxHtmlInfoService;
	@Autowired
	@Qualifier("queryReportService")
	private QueryReportService QueryReportService;

	@Override
	protected ZXVO postProcess(BaseNewZXReqBean<ZXCXA01QueryReports> reqBean,
							   BaseNewZXResBean<ZXCXA01ResponseReport> resBean) throws Exception {
		// 先查询是否存在已有的查询结果,如果已有那么直接返回不进行落库
		/*String certCode = reqBean.getQryRptsInfArry().get(0).getCertNo();
		if (certCode.length() == 18) {
			log.info("身份证号：" + certCode);
			return new ZXVO(Boolean.TRUE, certCode); // 挡板 SIT测试 TODO
		}*/

		ZXCXA01ResponseReport rprtHeadStruct = resBean.getRprtHeadStruct();
		String reportId = rprtHeadStruct.getRprtNo();
		ZXVO zxvo = new ZXVO(Boolean.TRUE, reportId);
		ZXJsonInfoVO queryReportVo = new ZXJsonInfoVO();
		queryReportVo.setReportId(reportId);
		if (zxJsonInfoService.queryByPk(queryReportVo) != null) {
			log.info("已存在查询结果，不进行落库，报告编号：" + reportId);
			return zxvo;
		}
		String reportTime=rprtHeadStruct.getRprtTm().replace("T"," ");
		String cusName = rprtHeadStruct.getBeQryPrsnNm();
		String certType=rprtHeadStruct.getBeQryPrsnIdentTp();
		String certCode = rprtHeadStruct.getBeQryPrsnIdentNo();
		String user=rprtHeadStruct.getQryBrchCd();
		String queryReason=rprtHeadStruct.getQryRsnCd();
		ZXJsonInfoVO ZXJsonInfoVO=new ZXJsonInfoVO();
		ZXJsonInfoVO.setReportId(reportId);
		ZXJsonInfoVO.setCusName(cusName);
		ZXJsonInfoVO.setCertType(certType);
		ZXJsonInfoVO.setCertCode(certCode);
		ZXJsonInfoVO.setQueryReason(rprtHeadStruct.getQryRsnCd());
		ZXJsonInfoVO.setJsonContent(resBean.getJSONFmtCrRfrncRprt());
		ZXJsonInfoVO.setCreateTime(DateUtility.getCurrDateTime());
		ZXJsonInfoVO.setReportTime(reportTime);
		ZXHtmlInfoVO zxHtmlInfoVO =new ZXHtmlInfoVO();
		zxHtmlInfoVO.setReportId(reportId);
		zxHtmlInfoVO.setCusName(cusName);
		zxHtmlInfoVO.setCertCode(certCode);
		//html Base64解码之后再存数据库
		byte[] bytes = Base64.decodeBase64(resBean.getHTMLFmtCrRfrncRprt());
		String html=new String(bytes,"UTF-8");

		zxHtmlInfoVO.setContent(html);
		QueryReportVO queryReport=new QueryReportVO();
		queryReport.setReportId(reportId);
		queryReport.setReportTime(reportTime);
		queryReport.setCername(cusName);
		queryReport.setCertype(certType);
		queryReport.setCercode(certCode);
		queryReport.setUser(user);
		queryReport.setQueryReason(queryReason);
		Optional.ofNullable(zxHtmlInfoVO).ifPresent(Try.ofConsumer(zxHtmlInfoService::insert));
		Optional.ofNullable(ZXJsonInfoVO).ifPresent(Try.ofConsumer(zxJsonInfoService::insert));
		Optional.ofNullable(queryReport).ifPresent(Try.ofConsumer(QueryReportService::insertQueryReport));
		log.info("征信JSON/XML/HTML格式查询结果落库完成，报告编号：" + reportId);
		return zxvo;
	}

}
